package com.yunquan.ohana.utils

import android.util.Base64
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher


object RSAUtils {

    private const val ALGORITHM = "RSA"

    const val PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhNLP5yuyZYhvbcLG2VHZH4j9lpF8LIF88fMKxa1JkorMoI9GF5hsXk/SMxHLCt2Yxj5HW/tLua3ftY/03P8Y5kKYd7VuQa4Mxtem4Xz/zNbEYkh3NHWlK+kwrHSLQ6rcwa++W8dC22usqgdOGignGUS9kkYeHsVZrl3V7I0FUwhqV2opwzX3tqlNBKonlJRsWk6I9BoaJWDPWGGZQ7oJ1JGuw0PWSWyNMkJvEeKSsSGmlfcFRR0NAwoqzgpnxNgBWlRaOoVZvRrUTz/7II2ycYsRQnldfs1p7T7VcQSE6LaPBFfd8IC0zvHDRBCxvYDcuCrLiNktvIrv54fTvhoNoQIDAQAB"

    fun createKey(): KeyPair {
        val mPair = KeyPairGenerator.getInstance(ALGORITHM)
        val keyPair = mPair.genKeyPair()
        //输出秘钥到控制台
        val publicKey = keyPair.public
        val privateKey = keyPair.private
        val publicKeyEncoded = publicKey.encoded
        val privateKeyEncoded = privateKey.encoded
        val publicKeyBase64 = Base64.encode(publicKeyEncoded, Base64.DEFAULT)
        val privateKeyBase64 = Base64.encode(privateKeyEncoded, Base64.DEFAULT)
        println("公钥：${String(publicKeyBase64, Charsets.UTF_8)}")
        println("私钥：${String(privateKeyBase64, Charsets.UTF_8)}")
        return keyPair
    }

    /**
     * 私钥加密
     * @param privateKeyStr 私钥
     * @param content 内容
     * @return String 加密数据
     */
    fun privateKeyEncrypt(privateKeyStr: String?, content: String): String {
        try {
            val decodeKey: ByteArray = Base64.decode(privateKeyStr, Base64.DEFAULT)
            val keySpec = PKCS8EncodedKeySpec(decodeKey)
            val keyFactory = KeyFactory.getInstance(ALGORITHM)
            val privateKey = keyFactory.generatePrivate(keySpec)
            val cipher = Cipher.getInstance(ALGORITHM)
            cipher.init(Cipher.ENCRYPT_MODE, privateKey)
            val bytes = cipher.doFinal(content.toByteArray())
            val base64 = Base64.encode(bytes,Base64.DEFAULT)
            return String(base64, Charsets.UTF_8)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    /**
     * 私钥解密
     * @param privateKeyStr 私钥
     * @param content 内容
     * @return String 明文数据
     */
    fun privateKeyDecrypt(privateKeyStr: String?, content: String?): String {
        try {
            val decodeKey: ByteArray = Base64.decode(privateKeyStr, Base64.DEFAULT)
            val keySpec = PKCS8EncodedKeySpec(decodeKey)
            val keyFactory = KeyFactory.getInstance(ALGORITHM)
            val privateKey = keyFactory.generatePrivate(keySpec)
            val cipher = Cipher.getInstance(ALGORITHM)
            cipher.init(Cipher.DECRYPT_MODE, privateKey)
            val base64 = Base64.decode(content, Base64.DEFAULT)
            val bytes = cipher.doFinal(base64)
            return String(bytes, Charsets.UTF_8)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    /**
     * 公钥加密
     * @param publicKeyStr 公钥
     * @param content 内容
     * @return String 加密数据
     */
    fun publicKeyEncrypt(publicKeyStr: String?, content: String): String {
        try {
            val decodeKey: ByteArray = Base64.decode(publicKeyStr, Base64.DEFAULT)
            val keySpec = X509EncodedKeySpec(decodeKey)
            val keyFactory = KeyFactory.getInstance(ALGORITHM)
            val publicKey = keyFactory.generatePublic(keySpec)
            val cipher = Cipher.getInstance(ALGORITHM)
            cipher.init(Cipher.ENCRYPT_MODE, publicKey)
            val bytes = cipher.doFinal(content.toByteArray())
            val base64 = Base64.encode(bytes, Base64.DEFAULT)
            return String(base64, Charsets.UTF_8)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    /**
     * 公钥解密
     * @param publicKeyStr 公钥
     * @param content 内容
     * @return String 明文数据
     */
    fun publicKeyDecrypt(publicKeyStr: String?, content: String?): String {
        try {
            val decodeKey: ByteArray = Base64.decode(publicKeyStr, Base64.DEFAULT)
            val keyFactory = KeyFactory.getInstance(ALGORITHM)
            val keySpec = X509EncodedKeySpec(decodeKey)
            val publicKey = keyFactory.generatePublic(keySpec)
            val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
            cipher.init(Cipher.DECRYPT_MODE, publicKey)
            val base64 = Base64.decode(content, Base64.DEFAULT)
            L.i("Base64解码1：${base64.contentToString()}")
            val bytes = cipher.doFinal(base64)
            L.i("RSA解码1：${bytes.contentToString()}")
            val startIndex = bytes.indexOf(123)
            val temp = bytes.copyOfRange(startIndex, bytes.size)
            return String(temp)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

}

//公钥：MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuK/5u/IbiYKhn0b/Gt7TFWv1zDg+t0XXoj8T2TpEHOhTvchJqpiUNfR/uWyHn1uoBRi/s6dZ69uU5oDgaSXBDMzt/75hggQr7X1Uwy1bnopi/FCZooWCWk0xne39YMGz90cMXv5BedPvySWrv5BD1QSB8waEnLIH8tF6+nr6GMJatsGH15kPhw2rQNYdWZYiDoZ+fVJBEbKVjXgxqXlyc4qTAKhSnNlCBzZqXMLf0ptPIA+vSwhzFG1ioCHe+sKoZjt0PAJqgnnPer7thdtUlaoWC5FMq3zJqy6P6dIphPOy8Blv+VcnnPNjoLNK387hBY9L7mTbgAwmkQTAphvPJQIDAQAB
//私钥：MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC4r/m78huJgqGfRv8a3tMVa/XMOD63RdeiPxPZOkQc6FO9yEmqmJQ19H+5bIefW6gFGL+zp1nr25TmgOBpJcEMzO3/vmGCBCvtfVTDLVueimL8UJmihYJaTTGd7f1gwbP3Rwxe/kF50+/JJau/kEPVBIHzBoScsgfy0Xr6evoYwlq2wYfXmQ+HDatA1h1ZliIOhn59UkERspWNeDGpeXJzipMAqFKc2UIHNmpcwt/Sm08gD69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34, 44, 34, 112, 97, 115, 115, 119, 111, 114, 100, 34, 58, 34, 97, 108, 98, 117, 109, 50, 52, 54, 34, 44, 34, 117, 115, 101, 114, 110, 97, 109, 101, 34, 58, 34, 97, 108, 98, 117, 109, 34, 125]
//解密结果：{"broker":"tcp://81.71.163.85:1883","password":"album246","username":"album"}

//公钥：MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvzXK1F9bcayCQClNgMPuf0L+n8vb/EGb07Me0tL4DHhUnm8lO1SkjIGdSh8Xoehf2wFUBWyf17RlfuzrDPTpZSU5yu5msUDhGCNGXqBjr+wEfLpr9aKlwbvGtjZQVrWqweK68/ByiERxX4O6YNqGbKU5mAeNpw4Ubqn8zK+a46zhRtvUeFQ6Lmo4sALxnf/Y218f3tkSlq/Ef624tV4LuobUG28W9J4/eJQdph7BRvVGInNyJZSqC06ArT5+ZbEv2hhyRAD9P+81N6rcJv5BYukr2dVH/KztEbGa3NT8db4Iq9ydetL3rbU0+Cs428Ew4dufbxRtUm7ZHp8gxYSDWQIDAQAB
//私钥：MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/NcrUX1txrIJAKU2Aw+5/Qv6f y9v8QZvTsx7S0vgMeFSebyU7VKSMgZ1KHxeh6F/bAVQFbJ/XtGV+7OsM9OllJTnK7maxQOEYI0ZeoGOv7AR8umv1oqXBu8a2NlBWtarB4rrz8HKIRHFfg7pg2oZspTmYB42nDhRuqfzMr5rjrOFG29R4VDouajiwAvGd/9jbXx/e2RKWr8R/rbi1Xgu6htQbbxb0nj94lB2mHsFG9UYic3IllKoLToCtPn5lsS/aGHJEAP0/7zU3qtwm/kFi6SvZ1Uf8rO0RsZrc1Px1vgir3J160vettTT4KzjbwTDh259vFG1SbtkenyDFhINZAgMBAAECggEAdT5NrWT/FDeb8i2hOThqsBvrNx5wOEAehXOKjekQcc0CzdcG9FdVQlZjlMR14DA1PnuVAnJ1nHUf2vD4u4wc5Ikr47P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WHHkewgFFhLfDBllRG0LS0GFtyXFe//dsTFFLCOlcwnkcs=
//加密结果：bLQ527pvOkoikEESLgDhZRSrlOaV/Badr+XrwzM8H/pKGu6s4EhUyi4z0WHg+bs3CDXsnCX/4uDJu9jwMyZrBYI2FPI+LhYBv7N5RVRMVFD05Er53PuFQ3U5GbqPhVe7qEHV2xX+R57UFBXkJ9+jLtSbQy7ahDkXP1O+cudOIW9gFKdeb1bZHdvzPg/A5U7yJ0FvPKqAwQTo2lv8+L2tucQz7Y1bekL3DPV7THSiVBlr9Dbi2oFWbbKgPpjzEA7dO/ztSkxsl6hsSc7YikReDxY1ZPMICkBioRG5atowalKkR502hzmctsh1ejxovfk5ktDfb9hY1Gp/WzMQ7Lr5iA==
//[123, 34, 98, 114, 111, 107, 101, 114, 34, 58, 34, 116, 99, 112, 58, 47, 47, 56, 49, 46, 55, 49, 46, 49, 54, 51, 46, 56, 53, 58, 49, 56, 56, 51, 34, 44, 34, 112, 97, 115, 115, 119, 111, 114, 100, 34, 58, 34, 97, 108, 98, 117, 109, 50, 52, 54, 34, 44, 34, 117, 115, 101, 114, 110, 97, 109, 101, 34, 58, 34, 97, 108, 98, 117, 109, 34, 125]
//解密结果：{"broker":"tcp://81.71.163.85:1883","password":"album246","username":"album"}

//"X6k0kEPXmSKQfqqaCn9S2VJOFltJuVrO21cHEeU+ErMownzoNpj3AI019wnkqnhndZO6Z1gBBUguXzza0ybK807JmgrAnwcTqnAi1nz\/Ky8DLrQQcWk8XtDjwDYTYCn0\/1GF8317dphUfJf9IfKnU2L1DCn4B0oQBREb28ai4gLlFb9dybx8IsHgKwrQz9AffxgrAUrQ6hW5bTLOA6SlOvTmjtkhhvQt3NGaIwlngOXwNCOsMX7QRTkA7TXA8eWYkq8EFFpmfPAdi8rc\/cBm1WwQddSUzuKBJjje\/tysQpT7Vs+I4uzsvcv6xdDT3zuqUqIu8cRKicWyasHXmQNOwA==",